﻿using He.Framework.AttributeMapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace He.DAL
{
    /// <summary>
    /// 泛型缓存做性能优化
    /// 不同的T产生不同的副本
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SqlBuilder<T>
    {
        private static string FindOneSql = null;
        private static string InsertSql = null;
        private static string UpdatetSql = null;
        private static string DeleteSql = null;

        static SqlBuilder()
        {
            Type type = typeof(T);
            string columnStrings = string.Join(",", type.GetPropertiesWithoutKey().Select(p => $"[{p.GetMappingName()}]"));
            string valueStrings = string.Join(",", type.GetPropertiesWithoutKey().Select(p => $"@{p.GetMappingName()}"));
            InsertSql = $@"insert into [{type.GetMappingName()}] ({columnStrings}) values({valueStrings}) ";

            string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetMappingName()}]"));
            FindOneSql = $@"SELECT  {columnString}
                          FROM {type.GetMappingName()}
                            where Id=";

            string columnStringUpdate = string.Join(",", type.GetPropertiesWithoutKey().Select(p => $"{p.GetMappingName()}=@{p.GetMappingName()}"));
            UpdatetSql = $"update [{type.GetMappingName()}] set {columnStringUpdate} where Id=";

            DeleteSql = $"Delete from [{type.GetMappingName()}] where Id=@Id;";

        }

        public static string GetSql(SqlType sqlType)
        {
            switch (sqlType)
            {
                case SqlType.FindOne:
                    return FindOneSql;
                case SqlType.Insert:
                    return InsertSql;
                case SqlType.Update:
                    return UpdatetSql;
                case SqlType.Delete:
                    return DeleteSql;
                default:
                    throw new Exception("wrong SqlType");
            }
        }

    }
    public enum SqlType
    {
        FindOne,
        Insert,
        Update,
        Delete
    }
}
